package com.sgb.member.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.android.material.tabs.TabLayout;
import com.sgb.member.MemberConfig;
import com.sgb.member.PickCateType;
import com.sgb.member.R;
import com.sgb.member.databinding.FragmentMemberBusiness3Binding;
import com.sgb.member.di.DaggerMemberFragComponent;
import com.sgb.member.di.MemberFragModule;
import com.sgb.member.entity.MaterialFilterJson;
import com.sgb.member.entity.MemberGoodsListEntity;
import com.sgb.member.ui.activity.MemberBusinessActivity;
import com.sgb.member.ui.adapter.HomeOtherMemberAdapter;
import com.sgb.member.ui.adapter.TabAdapter;
import com.sgb.member.view_model.BusinessGoodsFragModel3;
import com.sgb.member.weight.MatterChooseWindow2;
import com.sgb.member.weight.ScreenTextView;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.XCustomTabLayout;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.CopyUtils;
import com.swgk.core.view.selection.XChooseDialog;
import com.swgk.core.view.selection.XChooseEntity;
import com.swgk.core.xrecyclerview.LoadingMoreFooter;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.inject.Inject;

/**
 * 供方会员报价页面
 */
public class BusinessGoodsFragment3 extends AppLazyFragment implements XChooseDialog.DialogCallBackImpl {

    @Inject
    public BusinessGoodsFragModel3 sModel;
    private FragmentMemberBusiness3Binding mBinding;
    private HomeOtherMemberAdapter<MemberGoodsListEntity> mAdapter;
    private String mNo0 = ""; // "行业");
    private String mNo1 = ""; // "类型");
    private String mNo2 = ""; // "类别");
    private String mNo3 = ""; // "品名");
    private final List<String> mNo4 = new ArrayList<>(); // 其他参数
    private String mNo5 = ""; // "经营地址");
    private String mNo51 = ""; // "经营地址");
    private String mNo52 = ""; // "经营地址");
    private String mNo6 = ""; // "距离");
    private String mNo7 = ""; // "价格排序");
    private String mBestSellers = ""; // 热销商品1 默认为空
    private String mPromotions = "";  // 促销商品1 默认为空
    private String member_level = "";//会员等级
    private String brand_level = "";//品牌分级
    private String brand_name = "";//品牌名称
    private int mCurPos; // 主页面TAB下标
    private String first_level = "";
    private String second_level = "";
    private String three_level = "";

    private Map<String, CommonPopEntity> mStr = new HashMap<>();
    private List<CommonPopEntity> datas =new ArrayList<>();

    // 经营地址Popup
    private ThreeLevelAreaWindow mAddressPop;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;
    private boolean noMoreData = false;
    private TabAdapter tabAdapter;

    public static BusinessGoodsFragment3 newInstance(int position, CommonPopEntity entity) {
        BusinessGoodsFragment3 fragment = new BusinessGoodsFragment3();
        Bundle bundle = new Bundle();
        bundle.putInt("INDEX", position);
        bundle.putSerializable("ENTITY", entity);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMemberFragComponent.builder()
                .appComponent(appComponent)
                .memberFragModule(new MemberFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_member_business_3, container, false);
        mBinding.setLifecycleOwner(this);
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        mCurPos = getArguments().getInt("INDEX", 0);
        //主页面顶部点击对象
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.chooseLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < mNameArray.size(); i++) {
                    XChooseEntity chooseEntity = mData.get(mData.keyAt(i));
                    if (chooseEntity != null) {
                        if (chooseEntity.getList() == null || chooseEntity.getList().size() == 0) {
                            if (mCurPos == 0) {
                                if (chooseEntity.getSort() == PickCateType.TYPE_1 ||
                                        chooseEntity.getSort() == PickCateType.TYPE_7 ||
                                        chooseEntity.getSort() == PickCateType.TYPE_8 ||
                                        chooseEntity.getSort() == PickCateType.TYPE_9) {
                                    loadOtherData();
                                    return;
                                }
                            } else {
                                if (chooseEntity.getSort() == PickCateType.TYPE_7 ||
                                        chooseEntity.getSort() == PickCateType.TYPE_8 ||
                                        chooseEntity.getSort() == PickCateType.TYPE_9) {
                                    loadOtherData();
                                    return;
                                }
                            }
                        }
                    }
                }
                mChooseDialog.initData(mData, mFilters);
                sModel.getAddressModel(PickCateType.TYPE_7);
                mChooseDialog.showDialog();
            }
        });
        mNo0 = "";
        lat = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, "");
        lon = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, "");
        initChooseDialog();
        initPopup();
        initRecyclerTab();
        initRecycler();
    }

    private void initRecyclerTab() {
        tabAdapter = new TabAdapter(datas, requireContext());
        tabAdapter.setmMatterChoose((entity, select) -> {
            matterChoose(entity, select);
        });
        mBinding.rvTab.setAdapter(tabAdapter);
    }

    private void matterChoose(CommonPopEntity entity, ScreenTextView select) {
        select.contentSelectRed(true, true);
        boolean isChange = false;
        MatterChooseWindow2 mNameWindow5 = new MatterChooseWindow2(getContext());
        mNameWindow5.setVisible(false);
        mNameWindow5.setOnCloseBack(() -> {
            if ("全部".equals(entity.getCategoryName()) || "".equals(entity.getCategoryName())) {
                select.contentSelectRed(false, false);
                select.setText(entity.getTypeName());
            } else {
                select.contentSelectRed(true, false);
                select.setText(entity.getCategoryName());
            }
        });

        mNameWindow5.setOnCallBack(dictEntity -> {
            mStr.put(entity.getTypeName(), dictEntity);
            mNo4.clear();
            for (CommonPopEntity value : mStr.values()) {
                if (!"".equals(value.getNo())) {
                    mNo4.add(value.getTypeName());
                }
            }
            entity.setCategoryName(dictEntity.getTypeName());
            loadData(false, false);
            mFilters.put(Integer.parseInt(dictEntity.getId()), dictEntity.getSort());
        });

        mNameWindow5.setData(entity.getChildren());
        mNameWindow5.setBgView(mBinding.popLine);
        for (String s : mStr.keySet()) {
            if (entity.getTypeName().equals(s)) {
                mNameWindow5.setCheckDefaultById(mStr.get(s).getNo());
                isChange = true;
                break;
            } else {
                isChange = false;
            }
        }
        if (!isChange) {
            mNameWindow5.setCheckDefaultById(entity.getChildren().get(0).getNo());
        }
        new Handler().postDelayed(() -> mNameWindow5.showPopwindow(mBinding.popLine, 0, 0), 300);

    }

    @Override
    protected void onLazyLoad() {
        loadOtherData();
        loadData(false, true);
    }

    public void loadData(boolean isLoadMore) {
        loadData(isLoadMore, false);
    }

    public void loadData(boolean isLoadMore, boolean isFirst) {
        if (isLoadMore && noMoreData) {
            closeRecyclerRefreshing();
            return;
        }
        String text = ((MemberBusinessActivity) getActivity()).getSearchText();
        sModel.getGoodList(isLoadMore, text, mNo0, mNo1, mNo2, mNo3, mNo4, mNo5, mNo51, mNo6, mNo7,
                mPromotions, mBestSellers, lat, lon, member_level, brand_level, brand_name);
    }

    private void loadOtherData() {
        if (isListEmpty(PickCateType.TYPE_1)) {
            sModel.getFirstCategory(PickCateType.TYPE_1, mNo0, false); // 行业分类
        }
        if (isListEmpty(PickCateType.TYPE_7)) {
            sModel.getAddressModel(PickCateType.TYPE_7);  // 经营地址
        }
        if (isListEmpty(PickCateType.TYPE_8)) {
            sModel.getDistanceData(PickCateType.TYPE_8); // 距离
        }
        if (isListEmpty(PickCateType.TYPE_9)) {
            sModel.getPriceData(PickCateType.TYPE_9); // 价格排序
        }
        if (isListEmpty(PickCateType.TYPE_6)) {
            sModel.getMemberLevelData(PickCateType.TYPE_6, false); // 会员级别
        }
    }

    public void setAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (data != null && data.size() > 0) {
            scrData = data;
            if (TextUtils.isEmpty(mNo5)) {
                mAddressPop.setData(data, true);
            } else {
                String mName5 = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_NAME, "");
                mAddressPop.setDataAndPosition(data, mName5, "", "", true, true);
                mAddressPop.setDefaultByAreaCode(mAddressPop.getProvincePosition());
                mBinding.popup3.updateChooseTextStatus(1, mName5);
                mFilters.put(PickCateType.TYPE_7, mAddressPop.getProvincePosition());
            }
        } else {
            sModel.getAddressModel(PickCateType.TYPE_7);
        }
    }

    private void showTabLayout(List<CommonPopEntity> data, int pos) {
        if (data == null || data.size() == 0) {
            mBinding.tabLayout.setVisibility(View.GONE);
            return;
        }
        mBinding.tabLayout.setVisibility(View.VISIBLE);
        mBinding.tabLayout.removeAllTabs();
        mBinding.tabLayout.setOnTabSelectedListener(null);
        for (int i = 0; i < data.size(); i++) {
            mBinding.tabLayout.addTab(mBinding.tabLayout.newTab().setText(data.get(i).getTypeName()));
        }
        mBinding.tabLayout.setNormalColor(R.color.color_title_small);
        mBinding.tabLayout.addOnTabSelectedListener(data, new XCustomTabLayout.SimpleSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (isTabOneDialogRefresh) return;
                int pos = tab.getPosition();
                if (pos == 0){
                    datas.clear();
                    tabAdapter.notifyDataSetChanged();
                }
                if (pos == mFilters.get(PickCateType.TYPE_1)) return;
                XChooseEntity chooseEntity = mData.get(PickCateType.TYPE_1);
                mNo1 = chooseEntity.getItemId(pos);
                if (mNo1.equals("")) {
                    type = "";
                }
                first_level = mNo1;
                second_level = "";
                three_level = "";
                mNo2 = "";
                mNo3 = "";
                mNo4.clear();
                mFilters.put(PickCateType.TYPE_1, pos);
                updateOneCategoryData(chooseEntity.getList().get(pos), pos, false);
                updateBrandData(false);
                showChildTabLayout(null, 0);
                showChildTabLayout3(null, 0);
                loadData(false, false);
            }
        });
    }

    private void showChildTabLayout(List<CommonPopEntity> data, int index) {
        if (data == null || data.size() == 0) {
            mBinding.childTab.setVisibility(View.GONE);
            return;
        }
        mBinding.childTab.setVisibility(View.VISIBLE);
        mBinding.childTab.removeAllTabs();
        mBinding.childTab.setOnTabSelectedListener(null);
        for (int i = 0; i < data.size(); i++) {
            mBinding.childTab.addTab(mBinding.childTab.newTab().setText(data.get(i).getTypeName()));
        }
        mBinding.childTab.setNormalColor(R.color.color_title_small);
        mBinding.childTab.addOnTabSelectedListener(data, new XCustomTabLayout.SimpleSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (isTabTwoDialogRefresh) return;
                int pos = tab.getPosition();
                if (pos == 0){
                    datas.clear();
                    tabAdapter.notifyDataSetChanged();
                }
                if (pos == mFilters.get(PickCateType.TYPE_2)) return;
                XChooseEntity chooseEntity = mData.get(PickCateType.TYPE_2);
                mNo2 = chooseEntity.getItemId(pos);
                second_level = mNo2;
                three_level = "";
                mNo3 = "";
                mNo4.clear();
                mFilters.put(PickCateType.TYPE_2, pos);
                updateTwoCategoryData(chooseEntity.getList().get(pos), pos, false);
                showChildTabLayout3(null, 0);
                loadData(false, false);
            }
        });
        if (index > 0) {
            mBinding.childTab.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Objects.requireNonNull(mBinding.childTab.getTabAt(index)).select();
                    isTabTwoDialogRefresh = false;
                }
            }, 10);
        }
    }

    private void showChildTabLayout3(List<CommonPopEntity> data, int index) {
        if (data == null || data.size() == 0) {
            mBinding.childTab3.setVisibility(View.GONE);
            return;
        }
        mBinding.childTab3.setVisibility(View.VISIBLE);
        mBinding.childTab3.removeAllTabs();
        mBinding.childTab3.setOnTabSelectedListener(null);
        for (int i = 0; i < data.size(); i++) {
            mBinding.childTab3.addTab(mBinding.childTab3.newTab().setText(data.get(i).getTypeName()));
        }
        mBinding.childTab3.setNormalColor(R.color.color_title_small);
        mBinding.childTab3.addOnTabSelectedListener(data, new XCustomTabLayout.SimpleSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (isTabThreeDialogRefresh) return;
                int pos = tab.getPosition();
                if (pos == mFilters.get(PickCateType.TYPE_3)) return;
                XChooseEntity chooseEntity = mData.get(PickCateType.TYPE_3);
                mNo3 = chooseEntity.getItemId(pos);
                three_level = mNo3;
                mNo4.clear();
                mFilters.put(PickCateType.TYPE_3, pos);
                updateThreeCategoryData(chooseEntity.getList().get(tab.getPosition()), pos, false);
                //  sModel.getCateArguments( mNo3, false);
                loadData(false, false);
            }
        });
        if (index > 0) {
            mBinding.childTab3.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Objects.requireNonNull(mBinding.childTab3.getTabAt(index)).select();
                    isTabThreeDialogRefresh = false;
                }
            }, 10);
        }
    }

    /**
     * -------------------------------------initRecycler------------------------------------------
     */
    private void initRecycler() {
        TextView textView = mBinding.emptyView.findViewById(R.id.no_data_count);
        textView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setPullRefreshEnabled(true);
        mBinding.recyclerView.setLoadingMoreEnabled(true);
        LoadingMoreFooter footer = (LoadingMoreFooter) mBinding.recyclerView.getFootView();
        footer.setNoMoreHint("已经到底啦~");
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(false, false);
            }

            @Override
            public void onLoadMore() {
                loadData(true, false);
            }
        });
        initRecyclerAdapter(0);
    }

    private void initRecyclerAdapter(int index) {
        // 会员商品
        mAdapter = new HomeOtherMemberAdapter<>(getActivity(), R.layout.item_other_material_goods, null);
        mAdapter.setOnItemClick(new AdapterOnItemClick<MemberGoodsListEntity>() {
            @Override
            public void onItemClick(MemberGoodsListEntity goodsListEntity, int position) {
                // 商砼 == 7
                if ("7".equals(mNo1)) {
                    MaterialFilterJson filterJson = new MaterialFilterJson();
                    filterJson.setStrengthId(goodsListEntity.getSort());
                    MemberConfig.getInstance().startConcreteDetail(getActivity(), goodsListEntity.getId(), filterJson);
                } else {
                    MemberConfig.getInstance().startShopGoodsDetail(getContext(), goodsListEntity.getId(), "", goodsListEntity.getSkuid());
                }
            }
        });
        if (mAdapter != null) {
            mBinding.recyclerView.setAdapter(mAdapter);
        }
    }

    public void closeRecyclerRefreshing() {
        mBinding.recyclerView.refreshComplete();
        mBinding.recyclerView.loadMoreComplete();
    }

    public void showEmpty() {
        mAdapter.clearDatas();
        mBinding.emptyView.setVisibility(View.VISIBLE);
    }

    public void refreshRecycler(List<MemberGoodsListEntity> list, boolean isLoadMore, boolean noMoreData) {
        mBinding.recyclerView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setNoMore(noMoreData);
        closeRecyclerRefreshing();
        this.noMoreData = noMoreData;
        if (isLoadMore) {
            if (list != null && list.size() > 0) {
                mAdapter.addDatas(list);
            }
        } else {
            if (list != null && list.size() > 0) {
                mBinding.emptyView.setVisibility(View.GONE);
                mAdapter.setDatas(list);
            } else {
                mAdapter.clearDatas();
                mBinding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * ------------------------------- Popup ---------------------------------------------
     */
    private void initPopup() {
        mBinding.tvPromotion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtil.isEmpty(mPromotions)) {
                    mPromotions = "1";
                    mBinding.tvPromotion.refreshChoose(mPromotions, mBinding.tvPromotion.getKeyName(), 1);
                } else {
                    mPromotions = "";
                    mBinding.tvPromotion.refreshChoose(mPromotions, mBinding.tvPromotion.getKeyName(), 0);
                }
                loadData(false, false);
            }
        });
        mBinding.tvHotSales.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtil.isEmpty(mBestSellers)) {
                    mBestSellers = "1";
                    mBinding.tvHotSales.refreshChoose(mBestSellers, mBinding.tvHotSales.getKeyName(), 1);
                } else {
                    mBestSellers = "";
                    mBinding.tvHotSales.refreshChoose(mBestSellers, mBinding.tvHotSales.getKeyName(), 0);
                }
                loadData(false, false);
            }
        });
        mBinding.tvPromotion.setVisibility(View.VISIBLE);
        mBinding.tvHotSales.setVisibility(View.VISIBLE);
        mBinding.popup3.initPopup(mBinding.grayLayout, mBinding.popLine, null);
        initAddressPopup();
    }

    private String lat, lon = "";

    private void initAddressPopup() {
        mBinding.popup3.setOnClickListener(v -> {
            if (scrData == null) {
                sModel.getAddressModel(PickCateType.TYPE_7);
                return;
            }
            mBinding.popLine.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(mNo5) || !TextUtils.isEmpty(mNo51)) {
                mBinding.popup3.updateChooseTextStatus(-2, null);
            } else {
                mBinding.popup3.updateChooseTextStatus(-1, mBinding.popup3.getKeyName());
            }
            mAddressPop.showPopwindow0(mBinding.popLine);
        });
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setBgView(mBinding.grayLayout);
        mAddressPop.setMemberHeight();
        mAddressPop.setAreaSingle();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(false);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(false);
        mAddressPop.setSecondaryListIsGone(false);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                mNo5 = "";
                mNo51 = "";
                mNo52 = "";
                mFilters.put(PickCateType.TYPE_7, mAddressPop.getProvincePosition());
                addMainEntity(PickCateType.TYPE_72, new ArrayList<>());
                addMainEntity(PickCateType.TYPE_73, new ArrayList<>());
                mBinding.popup3.updateChooseTextStatus(0, mBinding.popup3.getKeyName());
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    mNo5 = entity.getProvinceNo();
                    mBinding.popup3.updateChooseTextStatus(1, entity.getProvinceName());
                    mFilters.put(PickCateType.TYPE_7, mAddressPop.getProvincePosition());
                    updateCityData(new CommonPopEntity(entity.getProvinceNo(), entity.getProvinceName()), mAddressPop.getProvincePosition(), false);
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        mNo51 = entity.getCityNo();
                        mBinding.popup3.updateChooseTextStatus(1, entity.getCityName());
                        mFilters.put(PickCateType.TYPE_72, mAddressPop.getmCityPosition());
                        updateAreaData(new CommonPopEntity(entity.getCityNo(), entity.getCityName()), mAddressPop.getmCityPosition(), false);
                        if (!TextUtils.isEmpty(entity.getAreaNo())) {
                            mNo52 = entity.getAreaNo();
                            mBinding.popup3.updateChooseTextStatus(1, entity.getAreaName());
                            mFilters.put(PickCateType.TYPE_73, mAddressPop.getmAreaPosition());
                        }
                    }
                }
                //刷新数据
                loadData(false, false);
            }
        });
        mAddressPop.setOnDismissListener(() -> {
            mBinding.popLine.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(mNo5) || !TextUtils.isEmpty(mNo51)) {
                mBinding.popup3.updateChooseTextStatus(1, null);
            } else {
                mBinding.popup3.updateChooseTextStatus(0, mBinding.popup3.getKeyName());
            }
        });
    }

    /**
     * ------------------------------------ 侧滑刷选 ----------------------------------------
     */

    private XChooseDialog mChooseDialog;
    // 数据集
    private SparseArray<XChooseEntity> mData = new SparseArray<>();
    // 本地缓存筛选结果
    private SparseIntArray mFilters = new SparseIntArray();
    private SparseArray<String> mNameArray;
    // 存储品名关联数据index
    private List<Integer> mMultiKey;

    private void initChooseDialog() {
        mNameArray = new SparseArray<>();
        mNameArray.put(PickCateType.TYPE_1, "商品类型");
        mNameArray.put(PickCateType.TYPE_2, "类别");
        mNameArray.put(PickCateType.TYPE_3, "品名");
        mNameArray.put(PickCateType.TYPE_4, "品牌分级");
        mNameArray.put(PickCateType.TYPE_41, "品牌名称");
        mNameArray.put(PickCateType.TYPE_5, "品牌名称");
        mNameArray.put(PickCateType.TYPE_6, "会员级别");
        mNameArray.put(PickCateType.TYPE_7, "仓储地");
        mNameArray.put(PickCateType.TYPE_72, "市区");
        mNameArray.put(PickCateType.TYPE_73, "县/区");
        mNameArray.put(PickCateType.TYPE_8, "距离");
        mNameArray.put(PickCateType.TYPE_9, "价格排序");
        mMultiKey = new ArrayList<>();
        mChooseDialog = new XChooseDialog(getContext(), mNameArray);
        mChooseDialog.setCallBack(this);
        for (int i = 0; i < mNameArray.size(); i++) {
            int key = mNameArray.keyAt(i);
            addMainEntity(key, new ArrayList<>());
        }
    }

    public void setChooseItemData(int type, List<CommonPopEntity> data) {
        addMainEntity(type, data);
        switch (type) {
            case PickCateType.TYPE_1:
                showTabLayout(data, 0);
                break;
            case PickCateType.TYPE_2:
                showChildTabLayout(data, 0);
                break;
            case PickCateType.TYPE_3:
                showChildTabLayout3(data, 0);
                break;
            case PickCateType.TYPE_7:
                break;
            case PickCateType.TYPE_9:
                break;
        }
    }

    public void showLeftDialog(int type, List<CommonPopEntity> data) {
        mChooseDialog.addEntity(type, data);
        mChooseDialog.showDialog();
    }


    public void addMainEntity(int index, List<CommonPopEntity> list) {
        if (mData.get(index) != null) {
            if (list == null || list.size() == 0) {
                mData.get(index).setList(new ArrayList<>());
            } else {
                mData.get(index).setList(list);
            }
        } else {
            mData.put(index, new XChooseEntity(index, mNameArray.get(index), list));
        }
        mFilters.put(index, 0);
    }

    private boolean isListEmpty(int catType) {
        return mData.get(catType) != null &&
                (mData.get(catType).getList() == null || mData.get(catType).getList().size() == 0);
    }


    private String type = "";

    /**
     * 右侧弹窗选择后回调
     */
    @Override
    public void loadChildData(XChooseEntity entity, int pos) {
        switch (entity.getSort()) {
            case PickCateType.TYPE_1:
                updateOneCategoryData(entity.getList().get(pos), pos, true);
                updateBrandLeveData(pos, true);
                if (pos > 0) {
                    updateBrandData(true);
                }
                mChooseDialog.showDialog();
                break;
            case PickCateType.TYPE_2:
                updateTwoCategoryData(entity.getList().get(pos), pos, true);
                updateBrandData(true);
                mChooseDialog.showDialog();
                break;
            case PickCateType.TYPE_3:
                updateThreeCategoryData(entity.getList().get(pos), pos, true);
                updateBrandData(true);
                break;
            case PickCateType.TYPE_4://品牌分级
                type = entity.getList().get(pos).getId();
                updateBrandData(true);
                mChooseDialog.showDialog();
                break;
            case PickCateType.TYPE_41://品牌名称
//              updateBrandData(true);
                mChooseDialog.showDialog();
                break;
            case PickCateType.TYPE_5:
                mChooseDialog.showDialog();
                break;
            case PickCateType.TYPE_7:
                updateCityData(entity.getList().get(pos), pos, true);
                mChooseDialog.showDialog();
                break;
            case PickCateType.TYPE_72:
                updateAreaData(entity.getList().get(pos), pos, true);
                mChooseDialog.showDialog();
                break;
        }
    }


    private String city_no = "";

    private void updateCityData(CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        city_no = entity.getNo();
        if (isShowLeftDialog) {
            mChooseDialog.addEntity(PickCateType.TYPE_72, new ArrayList<>());
            mChooseDialog.addEntity(PickCateType.TYPE_73, new ArrayList<>());
        } else {
            addMainEntity(PickCateType.TYPE_72, new ArrayList<>());
            addMainEntity(PickCateType.TYPE_73, new ArrayList<>());
        }
        if (pos > 0) {
            sModel.getAddressCityData(scrData, entity.getNo(), PickCateType.TYPE_72, isShowLeftDialog);
        }
    }

    private void updateAreaData(CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        if (isShowLeftDialog) {
            mChooseDialog.addEntity(PickCateType.TYPE_73, new ArrayList<>());
        } else {
            addMainEntity(PickCateType.TYPE_73, new ArrayList<>());
        }
        if (pos > 0) {
            //String itemNo = mData.get(PickCateType.TYPE_72).getItemNo(mFilters.get(PickCateType.TYPE_72));
            sModel.getAddressAreaData(scrData, city_no, entity.getNo(), PickCateType.TYPE_73, isShowLeftDialog);
        }
    }

    /**
     * 更新类别相关数据集合
     * 类型
     */
    private void updateOneCategoryData(CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        if (pos == 0) {
            type = "";
        }
        first_level = entity.getId();
        second_level = "";
        three_level = "";
        List<CommonPopEntity> tempList = new ArrayList<>();
        if (isShowLeftDialog) {
            mChooseDialog.addEntity(PickCateType.TYPE_2, tempList);
            mChooseDialog.addEntity(PickCateType.TYPE_3, tempList);
            mChooseDialog.addEntity(PickCateType.TYPE_4, tempList);
            mChooseDialog.addEntity(PickCateType.TYPE_41, tempList);
            mChooseDialog.addEntity(PickCateType.TYPE_5, tempList);
            for (Integer integer : mMultiKey) {
                mChooseDialog.addEntity(integer, tempList);
            }
        } else {
            mNo4.clear();
            addMainEntity(PickCateType.TYPE_2, tempList);
            addMainEntity(PickCateType.TYPE_3, tempList);
            addMainEntity(PickCateType.TYPE_4, tempList);
            addMainEntity(PickCateType.TYPE_41, tempList);
            addMainEntity(PickCateType.TYPE_5, tempList);
            for (Integer integer : mMultiKey) {
                addMainEntity(integer, tempList);
            }
        }
        if (pos > 0) {
            sModel.getCategoryChoose(PickCateType.TYPE_2, entity.getId(), isShowLeftDialog);
        }
    }

    /**
     * 更新类别相关数据集合 类别
     */
    private void updateTwoCategoryData(CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        second_level = entity.getId();
        three_level = "";
        List<CommonPopEntity> tempList = new ArrayList<>();
        if (isShowLeftDialog) {
            mChooseDialog.addEntity(PickCateType.TYPE_3, tempList);
        } else {
            mNo4.clear();
            addMainEntity(PickCateType.TYPE_3, tempList);
            for (Integer integer : mMultiKey) {
                addMainEntity(integer, tempList);
            }
        }
        if (pos > 0) {
            sModel.getCategoryChoose(PickCateType.TYPE_3, entity.getId(), isShowLeftDialog);
        }
    }

    // 更新 品牌分级
    private void updateBrandLeveData(int p, boolean isShowLeftDialog) {
        List<CommonPopEntity> tempList = new ArrayList<>();
        if (isShowLeftDialog) {
            mChooseDialog.addEntity(PickCateType.TYPE_4, tempList);
            mChooseDialog.addEntity(PickCateType.TYPE_41, tempList);
            for (Integer integer : mMultiKey) {
                addMainEntity(integer, tempList);
            }
        }
        if (p > 0) {
            sModel.getBrandData(PickCateType.TYPE_4, isShowLeftDialog);
        }
    }

    // 更新 ->品牌名称
    private void updateBrandData(boolean isShowLeftDialog) {
        List<CommonPopEntity> tempList = new ArrayList<>();
        if (isShowLeftDialog) {
            mChooseDialog.addEntity(PickCateType.TYPE_41, tempList);//品牌名称
            for (Integer integer : mMultiKey) {
                mChooseDialog.addEntity(integer, tempList);
            }
        }
        sModel.getBrandNameData(PickCateType.TYPE_41, type,
                first_level, second_level, three_level, isShowLeftDialog);

    }

    /**
     * 更新规格型号乱七八糟的
     */
    private void updateThreeCategoryData(CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        three_level = entity.getId();
        List<CommonPopEntity> tempList = new ArrayList<>();
        if (isShowLeftDialog) {
            for (Integer integer : mMultiKey) {
                mChooseDialog.addEntity(integer, tempList);
            }
        } else {
            for (Integer integer : mMultiKey) {
                addMainEntity(integer, tempList);
            }
        }
        if (pos > 0) {
            sModel.getCateArguments(entity.getId(), isShowLeftDialog);
        } else {
            if (isShowLeftDialog) {
                mChooseDialog.showDialog();
            }
            datas.clear();
            tabAdapter.notifyDataSetChanged();
        }
    }

    public void setMultiChooseItemData(List<CommonPopEntity> data, CommonPopEntity all,
                                       boolean isShowLeftDialog) {
        int multiIndex = getMultiKey();
        if (data != null && data.size() > 0) {
            for (CommonPopEntity datum : data) {
                List<CommonPopEntity> children = datum.getChildren();
                CommonPopEntity all_;
                if (children != null && children.size() > 0) {
                    multiIndex += 1;
                    all_= new CommonPopEntity("","全部");
                    all_.setId(multiIndex+"");
                    all_.setSort(0);
                    children.add(0, all_);
                    for (int i = 0; i < children.size(); i++) {
                        children.get(i).setId(multiIndex + "");
                        children.get(i).setSort(i);
                    }
                    mNameArray.put(multiIndex, datum.getTypeName());
                    if (isShowLeftDialog) {
                        mChooseDialog.addEntity(multiIndex, datum.getTypeName(), children);
                    }
                    addMainEntity(multiIndex, children);
                    mMultiKey.add(multiIndex);
                }
            }
            datas.clear();
            datas.addAll(data);
            tabAdapter.notifyDataSetChanged();
        }
        if (isShowLeftDialog) {
            mChooseDialog.showDialog(false);
        }
    }

    private boolean isTabOneDialogRefresh;
    private boolean isTabTwoDialogRefresh;
    private boolean isTabThreeDialogRefresh;

    @Override
    public void result(SparseArray<XChooseEntity> data, SparseIntArray map) {
        mData = CopyUtils.deepPopEntityCopy(data);
        mFilters = map.clone();
        mNo4.clear();
        isTabOneDialogRefresh = true;
        isTabTwoDialogRefresh = true;
        isTabThreeDialogRefresh = true;
        for (int i = 0; i < mData.size(); i++) {
            int key = mData.keyAt(i);
            refreshItemValue(key, mFilters.get(key), true);
        }
        //第三级菜单筛选项列表刷新
        if (mBinding.childTab3.getVisibility() != View.VISIBLE){
            datas.clear();
        }
        tabAdapter.notifyDataSetChanged();
        isTabOneDialogRefresh = false;
        isTabTwoDialogRefresh = false;
        isTabThreeDialogRefresh = false;
        loadData(false, false);
    }

    private void refreshItemValue(int key, int value, boolean isDialog) {
        XChooseEntity entity = mData.get(key);
        mFilters.put(key, value);
        String itemNo = entity.getItemNo(value);
        switch (key) {
            case PickCateType.TYPE_1:
                mNo1 = entity.getItemId(value);
                int tabCount1 = mBinding.tabLayout.getTabCount();
                if (isDialog && tabCount1 > 0) {
                    Objects.requireNonNull(mBinding.tabLayout.getTabAt(value)).select();
                }
                break;
            case PickCateType.TYPE_2:
                mNo2 = entity.getItemId(value);
               int tabCount = mBinding.childTab.getTabCount();
                if (isDialog && tabCount > 0) {
                showChildTabLayout(entity.getList(), value);
               }
                mBinding.childTab.setVisibility(entity.getList().size() > 0 ? View.VISIBLE : View.GONE);
                break;
            case PickCateType.TYPE_3:
                mNo3 = entity.getItemId(value);
                int tabCount3 = mBinding.childTab3.getTabCount();
                if (isDialog && tabCount3 > 0) {
                   showChildTabLayout3(entity.getList(), value);
                }
                mBinding.childTab3.setVisibility(entity.getList().size() > 0 ? View.VISIBLE : View.GONE);
                break;
            case PickCateType.TYPE_4://品牌分级
                brand_level = entity.getItemId(value);
                brand_name = "";
                break;
            case PickCateType.TYPE_41://品牌名称
                brand_name = entity.getItemNo(value);
                break;
            case PickCateType.TYPE_5:
                if (value > 0) {
                    mNo4.add(entity.getItemNo(value));
                }
                break;
            case PickCateType.TYPE_7:
                mNo5 = entity.getItemNo(value);
                mBinding.popup3.refreshChoose(mNo5, entity.getItemName(value), value);
                mAddressPop.setDefPosition(value, 0);
                break;
            case PickCateType.TYPE_72:
                mNo51 = entity.getItemNo(value);
                mAddressPop.setDefPosition(mFilters.get(PickCateType.TYPE_7), value);
                if (value > 0) {
                    mBinding.popup3.refreshChoose(mNo51, entity.getItemName(value), value);
                }
                break;
            case PickCateType.TYPE_73:
                mNo52 = entity.getItemNo(value);
                mAddressPop.setDefPosition(mFilters.get(PickCateType.TYPE_7), mFilters.get(PickCateType.TYPE_72), value);
                if (value > 0) {
                    mBinding.popup3.refreshChoose(mNo52, entity.getItemName(value), value);
                }
                break;
            case PickCateType.TYPE_8:
                mNo6 = entity.getItemId(value);
                break;
            case PickCateType.TYPE_9:
                mNo7 = entity.getItemId(value);
                break;
            case PickCateType.TYPE_6://会员级别
                member_level = entity.getItemId(value);
                break;
            default:
                if (mMultiKey.contains(key) &&
                        entity != null && entity.getList() != null
                        && entity.getList().size() >0) {
                    mStr.put(entity.getTypeName(),entity.getList().get(value));
                    mNo4.add(entity.getItemName(value));
                    CommonPopEntity commonPopEntity ;
                   for(int i=0;i<datas.size();i++){
                       commonPopEntity = datas.get(i);
                       if(commonPopEntity.getTypeName().equals(entity.getTypeName())){
                           commonPopEntity.setCategoryName(entity.getItemName(value));
                       }
                   }
                    tabAdapter.notifyDataSetChanged();
                }
                break;
        }
    }

    private int getMultiKey() {
        return PickCateType.TYPE_5 * 10;
    }

    @Override
    public void reset() {
        mFilters.clear();
        resetMainData();
        result(mData, mFilters);
        mChooseDialog.initData(mData, mFilters);
        mChooseDialog.showDialog();

    }

    @Override
    public void onCancel() {
        mChooseDialog.initData(mData, mFilters);
    }

    private void resetMainData() {
        List<CommonPopEntity> tempList = new ArrayList<>();
        addMainEntity(PickCateType.TYPE_2, tempList);
        addMainEntity(PickCateType.TYPE_3, tempList);
        addMainEntity(PickCateType.TYPE_4, tempList);
        addMainEntity(PickCateType.TYPE_41, tempList);
        addMainEntity(PickCateType.TYPE_5, tempList);
        addMainEntity(PickCateType.TYPE_72, tempList);
        addMainEntity(PickCateType.TYPE_73, tempList);
        for (Integer integer : mMultiKey) {
            addMainEntity(integer, tempList);
        }
    }

}
